package com.bjpowernode.shop.filter;

import com.bjpowernode.shop.constants.GatewayConstants;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Slf4j //开启log日志输出
@Configuration //拦截器
public class GatewayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求地址
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        log.info("path:{}",path);

        //如果是登录操作，则放行
        if (GatewayConstants.WHITE_LIST.contains(path))
            return chain.filter(exchange);

        //非登录操作，验证是否带有token
        String authorization = request.getHeaders().getFirst(GatewayConstants.AUTHORIZATION_PREFIX);
        //有token则放行【hasText:null/""/" "都返回false】【isNoEmpty：null/""】
        if (StringUtils.hasText(authorization))
            return chain.filter(exchange);

        //没有token则抛出异常信息
        Map<String,Object> errorResult = new HashMap<>();
        errorResult.put("code",20401);
        errorResult.put("msg","token异常");

        //==将异常信息响应到浏览器==
        ServerHttpResponse response = exchange.getResponse();
        //设置响应头信息格式为utf8
        response.getHeaders().set(HttpHeaders.CONTENT_TYPE,GatewayConstants.JSON_UTF8_TYPE);
        try {
            //将Map集合转换为字节数据
            byte[] bytes = new ObjectMapper().writeValueAsBytes(errorResult);
            //构建响应信息
            DataBuffer wrap = response.bufferFactory().wrap(bytes);
            //向响应体写入响应信息
            Mono<Void> mono = response.writeWith(
                    //响应式编程
                    Mono.just(wrap)
            );
            return mono;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
